package com.bsg.upm.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.bsg.upm.check.BusinessSystemCheck;
import com.bsg.upm.check.CheckResult;
import com.bsg.upm.constant.OperateDictConstants;
import com.bsg.upm.constant.OperateDictTypeConstants;
import com.bsg.upm.dto.BusinessSubSystemDto;
import com.bsg.upm.dto.BusinessSystemDto;
import com.bsg.upm.entity.BusinessSubSystemEntity;
import com.bsg.upm.entity.BusinessSystemEntity;
import com.bsg.upm.entity.UserEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;
import com.bsg.upm.util.DateUtils;
import com.bsg.upm.util.PrimaryKeyUtils;

/**
 * 业务系统管理业务处理类
 * 
 * @author HCK
 *
 */
@Service
public class BusinessSystemService extends BaseService {

	@Resource
	private BusinessSubSystemService businessSubSystemService;

	@Resource
	private BusinessSystemCheck businessSystemCheck;

	/**
	 * 业务系统查询
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson list(Map<String, Object> paramMap) throws APIException {
		try {
			// 结果集
			JSONArray results = new JSONArray();

			// 获取指定条件的业务系统
			List<BusinessSystemEntity> businessSystems = businessSystemDao.list(paramMap);

			for (BusinessSystemEntity businessSystem : businessSystems) {
				// 构建业务系统展示对象
				BusinessSystemDto dto = buildShowDto(businessSystem, false);
				results.add(dto);
			}

			return RespJsonFactory.buildOK(results);
		} catch (Exception e) {
			logger.error("业务系统查询异常", e);
			throw new APIException("业务系统查询异常:" + e.getMessage());
		}
	}

	/**
	 * 业务系统详情
	 * 
	 * @param businessSystemId
	 *            业务系统编码
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson get(String businessSystemId) throws APIException {
		try {
			// 获取指定的业务系统
			BusinessSystemEntity businessSystem = businessSystemDao.get(businessSystemId);
			if (businessSystem == null) {
				return RespJsonFactory.build(HttpStatus.SC_GONE, "该业务系统不存在");
			}

			// 构建业务系统展示对象
			BusinessSystemDto dto = buildShowDto(businessSystem, true);

			return RespJsonFactory.buildOK(dto);
		} catch (Exception e) {
			logger.error("业务系统获取异常", e);
			throw new APIException("业务系统获取异常:" + e.getMessage());
		}
	}

	/**
	 * 业务系统新增
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson save(Map<String, Object> paramMap) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_ADD;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 业务系统新增检查
			CheckResult chkRS = businessSystemCheck.checkSave(paramMap);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			// 构建业务系统对象
			BusinessSystemEntity businessSystem = buildBusinessSystem(paramMap);
			businessSystemDao.save(businessSystem);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_BUSINESS_SYSTEM, operateAcion, businessSystem.getId(),
					businessSystem.getName(), businessSystem.getCreateDateTime());

			return RespJsonFactory.buildCreated();
		} catch (Exception e) {
			logger.error("业务系统" + operateAcionText + "异常", e);
			throw new APIException("业务系统" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 业务系统编辑
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson update(Map<String, Object> paramMap) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_UPDATE;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 业务系统编辑检查
			CheckResult chkRS = businessSystemCheck.checkUpdate(paramMap);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			// 构建业务系统对象
			BusinessSystemEntity businessSystem = buildBusinessSystemToUpdate(paramMap);
			businessSystemDao.update(businessSystem);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_BUSINESS_SYSTEM, operateAcion, businessSystem.getId(),
					businessSystem.getName());

			return RespJsonFactory.buildOK();
		} catch (Exception e) {
			logger.error("业务系统" + operateAcionText + "异常", e);
			throw new APIException("业务系统" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 业务系统删除
	 * 
	 * @param id
	 *            业务系统编码
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	@Transactional(rollbackFor = APIException.class)
	public RespJson remove(String id) throws APIException {
		// 操作动作
		String operateAcion = OperateDictConstants.ACTION_REMOVE;
		String operateAcionText = dictTypeCache.getTextFromCache(OperateDictTypeConstants.OPERATE_ACTION, operateAcion);
		try {
			// 获取指定的业务系统
			BusinessSystemEntity businessSystem = businessSystemDao.get(id);

			// 业务系统删除检查
			CheckResult chkRS = businessSystemCheck.checkRemove(businessSystem);
			if (chkRS.isError()) {
				return RespJsonFactory.build(chkRS.getStatus(), chkRS.getErrorMsg());
			}

			businessSystemDao.remove(id);

			// 保存操作日志
			saveOperateLog(OperateDictConstants.MODEL_BUSINESS_SYSTEM, operateAcion, businessSystem.getId(),
					businessSystem.getName());

			return RespJsonFactory.buildNoContent();
		} catch (Exception e) {
			logger.error("业务系统" + operateAcionText + "异常", e);
			throw new APIException("业务系统" + operateAcionText + "异常" + e.getMessage());
		}
	}

	/**
	 * 构建业务系统基础展示对象
	 * 
	 * @param businessSystem
	 *            业务系统对象
	 * @return 业务系统展示对象
	 */
	public BusinessSystemDto buildBusinessSystemBaseDto(BusinessSystemEntity businessSystem) {
		BusinessSystemDto dto = new BusinessSystemDto();
		dto.setId(businessSystem.getId());
		dto.setName(businessSystem.getName());
		dto.setDescription(businessSystem.getDescription());
		dto.setOwner(businessSystem.getOwner());
		dto.setCreateDateTime(DateUtils.dateTimeToString(businessSystem.getCreateDateTime()));
		return dto;
	}

	/**
	 * 构建业务系统展示对象
	 * 
	 * @param businessSystem
	 *            业务系统对象
	 * @param showDetail
	 *            是否展示详情
	 * @return 业务系统展示对象
	 */
	private BusinessSystemDto buildShowDto(BusinessSystemEntity businessSystem, boolean showDetail) {
		BusinessSystemDto dto = buildBusinessSystemBaseDto(businessSystem);
		List<BusinessSubSystemEntity> businessSubSystems = businessSystem.getBusinessSubSystems();
		List<BusinessSubSystemDto> businessSubSystemDtos = new ArrayList<>(businessSubSystems.size());
		dto.setBusinessSubSystems(businessSubSystemDtos);

		for (BusinessSubSystemEntity businessSubSystem : businessSubSystems) {
			BusinessSubSystemDto businessSubSystemDto = businessSubSystemService
					.buildBusinessSubSystemBaseDto(businessSubSystem);
			businessSubSystemDtos.add(businessSubSystemDto);
		}
		return dto;
	}

	/**
	 * 构建业务系统对象
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return 业务系统对象
	 */
	private BusinessSystemEntity buildBusinessSystem(Map<String, Object> paramMap) {
		BusinessSystemEntity businessSystem = new BusinessSystemEntity();
		businessSystem.setId(PrimaryKeyUtils.uniqueId());
		businessSystem.setName(StringUtils.trim((String) paramMap.get("name")));
		businessSystem.setDescription(StringUtils.trim((String) paramMap.get("description")));
		businessSystem.setCreateDateTime(systemDao.getCurrentDateTime());
		UserEntity user = getUser();
		String username = user.getUsername();
		businessSystem.setOwner(username);
		return businessSystem;
	}

	/**
	 * 构建业务系统对象用于更新操作
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return 业务系统对象
	 */
	private BusinessSystemEntity buildBusinessSystemToUpdate(Map<String, Object> paramMap) {
		BusinessSystemEntity businessSystem = businessSystemDao.get((String) paramMap.get("businessSystemId"));

		if (paramMap.containsKey("name")) {
			businessSystem.setName(StringUtils.trim((String) paramMap.get("name")));
		}

		if (paramMap.containsKey("description")) {
			businessSystem.setDescription(StringUtils.trim((String) paramMap.get("description")));
		}
		return businessSystem;
	}

}
